package com.tanhua.dubbo.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.exception.BusinessException;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Question;
import com.tanhua.common.pojo.RecommendUser;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.RandomIndexUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.ErrorResult;
import com.tanhua.dubbo.server.api.HuanXinApi;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.vo.NearUserVo;
import com.tanhua.dubbo.server.vo.TodayBest;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @ClassName: TanHuaService
 * @Author:王晨晗
 * @Description: 探花业务层
 * @Date: 2022/01/06/19:40
 */
@Service
@Slf4j
public class TanHuaService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RecommendUserService recommendUserService;
    @Autowired
    private QuestionService questionService;
    @Reference
    private HuanXinApi huanXinApi;
    @Reference
    private VisitorsApi visitorsApi;
    @Value("${tanhua.default.recommend.users}")
    private String defaultRecommendUsers;
    @Reference
    private UserLikeApi userLikeApi;
    @Autowired
    private IMService imService;
    @Reference
    private UserLocationApi userLocationApi;
    @Autowired
    private UserInfoService userInfoService;

    /**
     * @description 查询个人主页的个人信息
     * @param userId
     * @return
     */
    public TodayBest queryUserInfo(Long userId) {
        //查询用户的详细信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" ,userId);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        //判断是否为空
        if (ObjectUtil.isEmpty(userInfo)){
            return null;
        }
        //封装响应数据
        TodayBest todayBest = new TodayBest();
        todayBest.setId(userId);        //用户id
        todayBest.setAge(userInfo.getAge());        //年龄
        todayBest.setGender(userInfo.getSex().name().toLowerCase());  //性别
        todayBest.setNickname(userInfo.getNickName());  //昵称
        todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags() , ",")));     //标签
        todayBest.setAvatar(userInfo.getLogo());        //头像

        //缘分值
        User user = UserThreadLocal.get();
        todayBest.setFateValue(recommendUserService.queryScore(userId , user.getId()).longValue());

        //记录来访用户
        visitorsApi.saveVisitor(userId, user.getId(), "个人主页");

        return todayBest;
    }

    /**
     * @description 查询用户的默聊问题
     * @param userId
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = questionService.queryQuestion(userId);
        if(ObjectUtil.isNotEmpty(question)){
            return question.getTxt();
        }
        //默认的问题
        return "你的爱好是什么？";
    }

    /**
     * @description 回复用户默聊问题
     * @param userId
     * @param reply
     * @return
     */
    public void replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        //查询用户详细信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id" ,user.getId());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);

        //构建消息内容
        Map<String , Object> msg = new HashMap<>();
        msg.put("userId" , user.getId()); //当前用户id
        msg.put("huanXinId" , "HX_" + user.getId());  //环信用户id;
        msg.put("nickname" , userInfo.getNickName());  //用户昵称
        msg.put("strangerQuestion" , queryQuestion(userId));  //默聊问题
        msg.put("reply" , reply);  //回复

        //发送环信消息
        Boolean result = huanXinApi.sendMsgFromAdmin("HX_" + userId, HuanXinMessageType.TXT, JSONUtil.toJsonStr(msg));

        if (!result){
            throw new BusinessException(ErrorResult.error());
        }
    }

    /**
     * @description 查询探花卡片列表
     * @return
     */
    public List<TodayBest> queryCardsList() {
        //获取user信息
        User user = UserThreadLocal.get();
        int count = 50;     //获取推荐的数量

        //查询获取到的50条推荐用户
        List<RecommendUser> recommendUserList = recommendUserService.queryCardList(user.getId(), count);
        if (CollUtil.isEmpty(recommendUserList)){
            //推荐默认列表
            recommendUserList = new ArrayList<>();
            List<String> list = StrUtil.split(defaultRecommendUsers, ",");
            for (String userId : list) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Convert.toLong(userId));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);
            }
        }

        //从获取的50个用户中随机10个
        List<RecommendUser> result = new ArrayList<>();  //保存展示用户的集合
        int showCount = Math.min(10, recommendUserList.size());  //展示数
        List<Integer> randomIndexList = RandomIndexUtil.getRandomIndexList(0, recommendUserList.size(), showCount);  //获取随机得到的索引值
        for (Integer integer : randomIndexList) {
            RecommendUser recommendUser = recommendUserList.get(integer);
            result.add(recommendUser);
        }

        //获取集合中的用户id
        List<Object> userIdList = CollUtil.getFieldValues(result, "userId");
        //查询数据库,获取用户详细信息
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id" , userIdList);
        List<UserInfo> userInfoList = userInfoMapper.selectList(wrapper);
        //封装佳人信息
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());      //用户id
            todayBest.setAge(userInfo.getAge());        //年龄
            todayBest.setAvatar(userInfo.getLogo());    //头像
            todayBest.setGender(userInfo.getSex().name().toLowerCase());    //性别
            todayBest.setNickname(userInfo.getNickName());      //昵称
            todayBest.setTags(Convert.toStrArray(StrUtil.split(userInfo.getTags(), ',')));  //标签
            todayBest.setFateValue(0L);     //缘分值

            todayBests.add(todayBest);
        }
        return todayBests;
    }

    /**
     * @description 喜欢
     * @param likeUserId
     * @return
     */
    public void likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean result = userLikeApi.likeUser(user.getId(), likeUserId);
        if (!result) {
            throw new BusinessException(ErrorResult.loveError());   //喜欢失败
        }
        //判断是否相互喜欢
        if (userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            try {
                imService.contactUser(likeUserId);
            } catch (Exception e) {
                //判断是否保存成为好友成功.(如果已经是好友,那么会抛出异常
                log.error("互相喜欢,添加好友失败,用户可能已经是好友了~~ userid:" + user.getId() + " , likeUserId:" + likeUserId , e);
            }
        }
    }

    /**
     * @description 不喜欢
     * @param likeUserId
     * @return
     */
    public void notLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        Boolean result = userLikeApi.notLikeUser(user.getId(), likeUserId);
        if (!result){
            throw new BusinessException(ErrorResult.disloveError());       // 不喜欢失败
        }
    }

    /**
     * @description 查询附近的人
     * @param gender
     * @param distance
     * @return
     */
   /* public List<NearUserVo> queryNearUser(String gender, String distance) {
        //获取user信息
        User user = UserThreadLocal.get();
        //查询用户的地理位置
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());
        //获取不到用户地理位置,返回空
        if (ObjectUtil.isEmpty(userLocationVo)){
            return ListUtil.empty();
        }
        //查询以当前用户为中心的附近的用户
        List<UserLocationVo> userLocationVos = userLocationApi.queryUserFromLocation(
                userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Convert.toDouble(distance),
                1, 50);
        //判断集合是否为空, 返回空集合
        if (CollUtil.isEmpty(userLocationVos)){
            return ListUtil.empty();
        }
        //查询数据库获取用户的详细信息
        //获取附近人的id
        List<Object> userIds = CollUtil.getFieldValues(userLocationVos, "userId");
        //构建查询条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id" , userIds);
        //构建用户性别条件
        if(StrUtil.equalsIgnoreCase(gender, "man")){
            wrapper.eq("sex", SexEnum.MAN);
        }else if(StrUtil.equalsIgnoreCase(gender, "woman")){
            wrapper.eq("sex", SexEnum.WOMAN);
        }
        //执行查询
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        //封装响应数据
        List<NearUserVo> result = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //排除自己
            if(ObjectUtil.equals(userInfo.getUserId(), user.getId())){
                continue;
            }
            NearUserVo nearUserVo = new NearUserVo();
            nearUserVo.setUserId(userInfo.getUserId());     //用户id
            nearUserVo.setAvatar(userInfo.getLogo());       //头像
            nearUserVo.setNickname(userInfo.getNickName()); // 昵称

            result.add(nearUserVo);
        }

        return result;
    }*/

    //mongo查询附近的人
    public List<NearUserVo> queryNearUser1(String gender, String distance) {
        //获取user信息
        User user = UserThreadLocal.get();
        //查询用户的地理位置
        UserLocationVo userLocationVo = userLocationApi.queryByUserId1(user.getId());
        //获取不到用户地理位置,返回空
        if (ObjectUtil.isEmpty(userLocationVo)){
            return ListUtil.empty();
        }
        //查询以当前用户为中心的附近的用户
        List<UserLocationVo> userLocationVos = userLocationApi.queryUserFromLocation1(
                userLocationVo.getLongitude(),
                userLocationVo.getLatitude(),
                Convert.toDouble(distance),
                1, 50);
        //判断集合是否为空, 返回空集合
        if (CollUtil.isEmpty(userLocationVos)){
            return ListUtil.empty();
        }
        //查询数据库获取用户的详细信息
        //获取附近人的id
        List<Object> userIds = CollUtil.getFieldValues(userLocationVos, "userId");
        //构建查询条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id" , userIds);
        //构建用户性别条件
        if(StrUtil.equalsIgnoreCase(gender, "man")){
            wrapper.eq("sex", SexEnum.MAN);
        }else if(StrUtil.equalsIgnoreCase(gender, "woman")){
            wrapper.eq("sex", SexEnum.WOMAN);
        }
        //执行查询
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        //封装响应数据
        List<NearUserVo> result = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //排除自己
            if(ObjectUtil.equals(userInfo.getUserId(), user.getId())){
                continue;
            }
            NearUserVo nearUserVo = new NearUserVo();
            nearUserVo.setUserId(userInfo.getUserId());     //用户id
            nearUserVo.setAvatar(userInfo.getLogo());       //头像
            nearUserVo.setNickname(userInfo.getNickName()); // 昵称

            result.add(nearUserVo);
        }

        return result;
    }
}
